<template>
  <app-page>
    <mxp-refresh-page ref="mxpRefreshPageRef" :queryData="queryData">
      <view style="position: relative; box-sizing: border-box; height: 130px; padding-top: 30px; background: linear-gradient(180deg, #ffdf00, #fdbf00)">
        <view style="width: 100vw; height: 244rpx">
          <image
            src="/static/images/personal/diamond-top-bg.png"
            mode="scaleToFill"
            style="position: absolute; bottom: 0rpx; left: 0; z-index: 1; width: 100vw; height: 100px"
          ></image>
          <view class="diamond-box">
            <view>
              <text style="font-size: 15px; color: #522700">我的K币</text>
            </view>
            <view style="margin-top: 10px">
              <text style="font-size: 28px; font-weight: bolder; line-height: 24px; color: #522700">{{ userInfo?.virtualCoins || '0' }}</text>
              <text style="font-size: 15px; line-height: 15px; color: #522700">个</text>
            </view>
          </view>
        </view>
      </view>
      <view style="position: relative; z-index: 2; margin-top: -10px; border-radius: 10px 10px 0 0" :style="{ background: defThemeColor.bgColor }">
        <view style="display: flex; flex-direction: row; align-items: center; justify-content: space-between; padding: 10px 15px; padding-top: 20px">
          <view style="display: flex; flex-direction: row; align-items: center">
            <text style="margin-left: 4px; font-size: 16px; font-weight: bold; color: #000000">请选择充值金额</text>
          </view>
          <view hoverClass="hover" style="padding: 4px 0" @click="openPayNoticePopup">
            <text style="margin-left: 4px; font-size: 14px; color: #522700">《充值服务协议》</text>
          </view>
        </view>
        <template v-if="payList.length > 0">
          <view class="pay-list">
            <pay-select-item
              v-for="(item, index) in payList"
              :key="index"
              style="width: 100%"
              :productType="1"
              :active="currIndex === index"
              :productName="item.productName || ''"
              :productPrice="isToutiao && devicePlatform === 'ios' ? (item.productPrice || 0) * 10 : item.productPrice || 0"
              :marketingDesc="item.marketingDesc || ''"
              :recommendTags="item.recommendTags || ''"
              :unit="isToutiao && devicePlatform === 'ios' ? '钻' : '元'"
              @myClick="changeMoney(index)"
            ></pay-select-item>
          </view>
          <view class="hint-box">
            <text class="title">温馨提示：</text>
            <text class="hint">1. 虚拟物品付费后不支持退款</text>
            <text class="hint">
              2. 1{{ isToutiao && devicePlatform === 'ios' ? '钻' : '人民币' }}等于{{
                isToutiao && devicePlatform === 'ios' ? (priceVirtualRate || 100) / 10 : priceVirtualRate || 1000
              }}K币
            </text>
            <text class="hint">3. K币充值后不可反向兑换为人民币等其他法定货币</text>
            <text class="hint">4. 未满18岁的未成年,应在监护人同意或授权下充值</text>
          </view>
        </template>
        <view style="height: 100px"></view>
      </view>
    </mxp-refresh-page>
    <!-- #ifdef MP-TOUTIAO -->
    <service-button :offsetTop="15" :location="['15px', '95px']"></service-button>
    <!-- #endif -->
    <!-- 充值服务协议 -->
    <recharge-agreement-popup ref="rechargeAgreementPopupRef" :height="sys.windowHeight * 0.7"></recharge-agreement-popup>
  </app-page>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import AppPage from '@/components/app-page/app-page.vue';
  // #ifdef MP-TOUTIAO
  import ServiceButton from '@/components/pay/service-button/service-button.vue';
  // #endif
  import RechargeAgreementPopup from '@/components/page/recharge-agreement/recharge-agreement-popup.vue';
  import PaySelectItem from '@/components/pay/pay-select-item/pay-select-item.vue';
  import { defThemeColor } from '@/mxp-ui/mxp-tool/theme/theme';
  import {
    type RechargeService,
    createWebRechargeOrderAxios,
    createWechatDramaOrderAxios,
    dyCreateEpisodePayOrderAxios,
    getVirtualProductListAxios,
    queryOrderAxios,
  } from '@/api/pay';
  import { ksPay, ttOrderPay, webPay, wxOrderPay, wxOrderVirtualPay } from '@/utils/payUtil';
  import { useAppStore } from '@/pinia/app';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import { sleep } from '@/mxp-ui/mxp-tool/utils/rest';
  import { updateUserInfo } from '@/utils/page/user';
  import type { UserInfo } from '@/api/user';
  import { onPullDownRefresh } from '@dcloudio/uni-app';
  import MxpRefreshPage, { type Ins } from '@/mxp-ui/mxp-refresh-page/mxp-refresh-page.vue';
  import { useRefresh } from '@/mxp-ui/mxp-tool/hooks/useHooksRefresh.ts';

  const { mxpRefreshPageRef } = useRefresh(onPullDownRefresh);

  const sys = mxpGetSysInfoStore().getSysInfo();
  const rechargeAgreementPopupRef = ref<InstanceType<typeof RechargeAgreementPopup> | null>(null);

  const appStore = useAppStore();
  const isPay = ref(true);
  const payList = ref<RechargeService[]>([]);
  const currIndex = ref(0);
  const loading = ref(false);
  const userInfo = computed<UserInfo | undefined>(() => appStore.userInfo);
  const priceVirtualRate = computed(() => Number(appStore.baseDictInfo?.PRICE_VIRTUAL_RATE || '100'));
  const devicePlatform = computed(() => (sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform));
  const isToutiao = computed(() => sys.value.uniPlatform === 'mp-toutiao');

  /** 切换支付 */
  async function changeMoney(index: number) {
    if (!loading.value) {
      currIndex.value = index;
      if (isPay.value) {
        const item = payList.value[currIndex.value]!;
        try {
          loading.value = true;
          // #ifdef MP-TOUTIAO
          await openTTPay(item.productId);
          // #endif
          // #ifdef MP-WEIXIN
          await openWxPay(item.productId);
          // #endif
          // #ifdef MP-KUAISHOU
          await openKsPay(item.productId);
          // #endif
          // #ifdef WEB
          await openWebPay(item.productId);
          // #endif
          // #ifdef APP
          await openAppPay(item.productId);
          // #endif

          loading.value = false;
          // #ifndef WEB
          uni.showToast({ title: '充值成功', icon: 'success', position: 'bottom' });
          // #endif
        } catch (error) {
          console.log('充值失败====', error);
          // #ifndef WEB
          uni.showToast({ title: '充值失败', icon: 'none', position: 'bottom' });
          // #endif
          loading.value = false;
        }
      } else {
        uni.showToast({ title: '由于平台限制,暂不支持支付', icon: 'none', position: 'bottom' });
      }
    }
  }

  /** 微信支付 */
  async function openWxPay(productId?: number | undefined) {
    // #ifdef MP-WEIXIN
    try {
      uni.showLoading({ title: '加载中', mask: true });
      const wxOrder = await createWechatDramaOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        wxExportId: appStore.launchQuery?.wxExportId,
        wxFinderId: appStore.launchQuery?.wxFinderId,
        wxPromotionId: appStore.launchQuery?.wxPromotionId,
        channelId: appStore.launchQuery?.channelId,
        productType: 1,
        clickId: appStore.launchQuery?.clickid,
        productId,
        devicePlatform: devicePlatform.value,
        launchQueryPramas: appStore.newLaunchQuery || {},
      });
      uni.hideLoading();
      if (devicePlatform.value === 'ios') {
        await wxOrderPay(wxOrder.data.paymentDTO!);
      } else {
        await wxOrderVirtualPay(wxOrder.data);
      }
      uni.showLoading({ title: '正在获取支付结果', mask: true });
      await queryPaymentResults(wxOrder.data.outTradeNo!);
      uni.hideLoading();
      return Promise.resolve(true);
    } catch (error) {
      uni.hideLoading();
      return Promise.reject(error);
    }
    // #endif
  }
  /** 快手支付 */
  async function openKsPay(productId?: number | undefined) {
    // #ifdef MP-KUAISHOU
    try {
      uni.showLoading({ title: '加载中', mask: true });
      const ksOrder = await createWebRechargeOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        productType: 1,
        productId,
        devicePlatform: devicePlatform.value,
      });
      uni.hideLoading();
      await ksPay({ order_no: ksOrder.data.transactionId!, order_info_token: ksOrder.data.orderInfoToken! });
      uni.showLoading({ title: '正在获取支付结果', mask: true });
      await queryPaymentResults(ksOrder.data.outTradeNo!);
      uni.hideLoading();
      return Promise.resolve(true);
    } catch (error) {
      uni.hideLoading();
      console.log('error====', error);
      return Promise.reject(error);
    }
    // #endif
  }

  /** 抖音小程序支付 */
  async function openTTPay(productId?: number | undefined): Promise<boolean> {
    // #ifdef MP-TOUTIAO
    try {
      uni.showLoading({ title: '加载中', mask: true });
      const ttOrder = await dyCreateEpisodePayOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        channelId: appStore.launchQuery.channelId || undefined,
        productType: 1,
        clickId: appStore.launchQuery?.clickid,
        productId,
        devicePlatform: sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform,
        launchQueryPramas: appStore.launchQuery || {},
      });
      const payResult = await ttOrderPay(ttOrder.data);
      uni.showLoading({ title: '正在获取支付结果', mask: true });
      await queryPaymentResults(payResult.outTradeNo!);
      uni.hideLoading();
      return Promise.resolve(true);
    } catch (error) {
      uni.hideLoading();
      return Promise.reject(error);
    }

    // #endif
  }

  /** 网页支付 */
  async function openWebPay(productId?: number | undefined) {
    // #ifdef WEB
    try {
      const webOrder = await createWebRechargeOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        productType: 1,
        productId,
        devicePlatform: devicePlatform.value,
      });
      webPay(webOrder.data.alipayForm!);
      return Promise.resolve(true);
    } catch (error) {
      return Promise.reject(error);
    }
    // #endif
  }
  /** APP支付 */
  async function openAppPay(productId?: number | undefined): Promise<boolean> {
    // #ifdef APP
    try {
      const order = await createWebRechargeOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        productType: 1,
        productId,
        devicePlatform: sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform,
      });
      // await pay(order.data);
      await queryPaymentResults(order.data.outTradeNo!);
      return Promise.resolve(true);
    } catch (error) {
      return Promise.reject(error);
    }
    // #endif
  }

  /** 打开充值须知 */
  function openPayNoticePopup() {
    rechargeAgreementPopupRef.value?.show();
  }

  /** 加载中 */
  async function queryData(ins: Ins) {
    try {
      const res = await getVirtualProductListAxios({
        productType: 1,
        referralLinkId: appStore.launchQuery?.referralLinkId,
        devicePlatform: devicePlatform.value,
        wxFinderId: appStore.launchQuery?.wxFinderId,
        wxExportId: appStore.launchQuery?.wxExportId,
        wxPromotionId: appStore.launchQuery?.wxPromotionId,
      });
      payList.value = res.data.productList || [];
      currIndex.value = res.data.selectIndex;
      isPay.value = res.data.pay;
      ins.setSuccess();
    } catch (error) {
      payList.value = [];
      ins.setMoreEmpty('fail_load', error.msg || '获取数据失败，BD0001');
    }
  }

  /**
   * 查询支付结果,并更新用户信息(K币和会员状态)
   */
  async function queryPaymentResults(outOrderNo: string) {
    try {
      await sleep(1000);
      const queryRes = await queryOrderAxios(outOrderNo);
      if (queryRes.data.status === 1) {
        await updateUserInfo(); // 更新个人资料
        return Promise.resolve(true);
      } else {
        return Promise.resolve(false);
      }
    } catch (error) {
      return Promise.resolve(false);
    }
  }
</script>

<style lang="scss" scoped>
  .diamond-box {
    position: relative;
    z-index: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100px;
    padding-bottom: 10px;
    padding-left: 80rpx;
  }

  .pay-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 15px;
    justify-content: space-between;
    justify-items: center;
    padding: 15px;
  }

  .hover {
    opacity: 0.7;
  }

  .hint-box {
    display: flex;
    flex-direction: column;
    padding: 15px;
    padding-top: 0;

    .title {
      margin-bottom: 6px;
      font-size: 12px;
      font-weight: bold;
      color: #666666;
      word-break: break-all;
      word-wrap: break-word;
      white-space: normal !important;
    }

    .hint {
      margin-bottom: 6px;
      font-size: 12px;
      color: #999999;
      word-break: break-all;
      word-wrap: break-word;
      white-space: normal !important;
    }
  }
</style>
